package com.EVO.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.sql.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Util {
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public  static Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/javamysql","root","L4213416");
    }

    /**
     * 重载getConnection()方法
     */
    public  static Connection getConnection(HttpServletRequest request) throws SQLException {
        ServletContext application = request.getServletContext();
        Map<Connection,Boolean> map = (Map) application.getAttribute("key1");
        Iterator it = map.keySet().iterator();
        Connection conn = null;
        while(it.hasNext()){
            conn = (Connection) it.next();
            if(map.get(conn)){
                map.put(conn,false);
                break;
            }
        }
        return conn;
    }
    /**
     * 释放资源
     * @param conn
     * @param stmt
     * @param rs
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs){
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 重载close()方法
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs,HttpServletRequest request){
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        ServletContext application = request.getServletContext();
        Map map = (Map) application.getAttribute("key1");
        map.put(conn,true);
        application.setAttribute("key1",map);

    }
}
